// services/article_service.go
package services

import (
	"gorm_project/models"
	"gorm_project/repositories"
)

type ArticleService struct {
	articleRepo *repositories.ArticleRepository
}

func NewArticleService(articleRepo *repositories.ArticleRepository) *ArticleService {
	return &ArticleService{
		articleRepo: articleRepo,
	}
}

type CreateArticleRequest struct {
	Title      string   `json:"title" binding:"required"`
	Content    string   `json:"content" binding:"required"`
	Summary    string   `json:"summary"`
	CoverImage string   `json:"coverImage"`
	CategoryID uint     `json:"categoryId" binding:"required"`
	Tags       []string `json:"tags"`
}

func (s *ArticleService) CreateArticle(req CreateArticleRequest, userID uint) (*models.Article, error) {
	article := &models.Article{
		Title:      req.Title,
		Content:    req.Content,
		Summary:    req.Summary,
		CoverImage: req.CoverImage,
		CategoryID: req.CategoryID,
		UserID:     userID,
		Status:     "draft",
	}

	// 处理标签
	if len(req.Tags) > 0 {
		var tags []models.Tag
		for _, tagName := range req.Tags {
			tags = append(tags, models.Tag{Name: tagName})
		}
		article.Tags = tags
	}

	if err := s.articleRepo.Create(article); err != nil {
		return nil, err
	}

	return article, nil
}

func (s *ArticleService) GetPublishedArticles() ([]models.Article, error) {
	return s.articleRepo.FindPublished()
}

func (s *ArticleService) GetArticleByID(id uint) (*models.Article, error) {
	article, err := s.articleRepo.FindByID(id)
	if err != nil {
		return nil, err
	}

	// 增加阅读量
	go s.articleRepo.IncreaseViews(id)

	return article, nil
}

func (s *ArticleService) GetArticlesByCategory(categoryID uint) ([]models.Article, error) {
	return s.articleRepo.FindByCategory(categoryID)
}
